﻿/***********************************************************************
 * <copyright file="PermissionController.cs" company="B/S JSC">
 * -->    Copyright (C) statement. All right reserved
 * </copyright>
 * 
 * Created:   Hoang Bich Son 
 * Email:    sonhb@newman.vn
 * Website:
 * Create Date: Friday, March 7, 2014
 * Usage: 
 * 
 * RevisionHistory: 
 * Date         Author               Description 
 * 
 * ************************************************************************/

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using DXWebApplication.Areas.Administrators.Models;
using DXWebApplication.Repositories.Implementations.Security;
using DXWebApplication.SecurityServiceReference;
using Newtonsoft.Json;

namespace DXWebApplication.Areas.Administrators.Controllers.Security
{
    /// <summary>
    /// PermissionController
    /// </summary>
    public class PermissionController : AdminBaseController, IAdminBaseController<PermissionModel>
    {
        private readonly PermissionRepository _permissionRepository;
        private readonly SiteRepository _siteRepository;
        private readonly PermissionInSiteRepository _permissionInSiteRepository;

        public PermissionController()
        {
            _permissionRepository = new PermissionRepository();
            _siteRepository = new SiteRepository();
            _permissionInSiteRepository = new PermissionInSiteRepository();
        }

        /// <summary>
        /// Inserts this instance.
        /// </summary>
        /// <returns></returns>        
        [HttpGet]
        public PartialViewResult Insert()
        {
            var result = new PermissionModel();
            return PartialView("PermissionDetail", result);
        }

        /// <summary>
        /// Inserts the specified model.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        [HttpPost]
        public JsonResult Insert(PermissionModel model)
        {
            var msg = string.Empty;
            if (ModelState.IsValid)
            {
                msg = _permissionRepository.Insert(model.FromModel());
            }
            return Json(new { message = msg });
        }

        /// <summary>
        /// Updates this instance.
        /// </summary>
        /// <param name="idJson">The identifier json.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        [HttpGet]
        public PartialViewResult Update(string idJson)
        {
            try
            {
                var idList = JsonConvert.DeserializeObject<List<int>>(idJson);
                var model = new PermissionModel();
                if (idList.Count == 1)
                {
                    if (idList[0] > 0)
                    {
                        model = _permissionRepository.Get(idList[0]).ToModel();
                    }
                }
                return PartialView("PermissionDetail", model);
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// Updates the specified model.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        [HttpPost]
        public JsonResult Update(PermissionModel model)
        {
            var msg = string.Empty;
            if (ModelState.IsValid)
            {
                msg = _permissionRepository.Update(model.FromModel());
            }
            return Json(new { message = msg });
        }

        /// <summary>
        /// Deletes the specified ids.
        /// </summary>
        /// <param name="idJson">The identifier json.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public JsonResult Delete(string idJson)
        {
            string msg;
            try
            {
                var idList = JsonConvert.DeserializeObject<IList<int>>(idJson);
                msg = _permissionRepository.Delete(idList);
            }
            catch (Exception)
            {
                return Json(new { message = NmResources.MessageResource.Exception }, JsonRequestBehavior.AllowGet);
            }
            return Json(new { message = msg }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// Gets the paged.
        /// </summary>
        /// <param name="currentPage">The current page.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public PartialViewResult GetPaged(int currentPage = 1)
        {
            var totalPage = 0;
            var result = _permissionRepository.GetPaged(ref totalPage, currentPage);
            ViewBag.TotalPage = totalPage;
            ViewBag.CurrentPage = currentPage;
            return PartialView("Permission", result.ToModel());
        }

        /// <summary>
        /// Assigns to site.
        /// </summary>
        /// <param name="idJson">The identifier json.</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult AssignToSite(string idJson)
        {
            try
            {
                var idList = JsonConvert.DeserializeObject<List<int>>(idJson);
                if (idList.Count == 1)
                {
                    var perId = idList[0];
                    if (perId > 0)
                    {
                        ViewBag.AssignToSite = AssignToSiteHtml(perId);
                        ViewBag.PerId = perId;
                    }
                }
                return PartialView();
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// Assigns to site.
        /// </summary>
        /// <param name="perId">The per identifier.</param>
        /// <param name="tableJson">The table json.</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult AssignToSite(int perId, string tableJson)
        {
            var msg = string.Empty;
            try
            {
                var jsonData = JsonConvert.DeserializeObject<List<PermissionInSiteDto>>(tableJson);                
                if (perId > 0 && jsonData.Count > 0)
                {
                    msg = _permissionInSiteRepository.AssignToSite(perId, jsonData);
                }
            }
            catch (Exception)
            {
                return Json(new { message = NmResources.MessageResource.Exception });
            }
            return Json(new { message = msg });
        }

        #region Assign
        /// <summary>
        /// Assigns to site HTML.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <returns></returns>
        public MvcHtmlString AssignToSiteHtml(int id)
        {
            var siteList = _siteRepository.GetList();
            var permissionInSites = _permissionInSiteRepository.GetPermissionInSiteByPermissionId(id);
            var parents = siteList.Where(x => x.ParentId == 0);
            var lev = 0;
            var tag = new StringBuilder();
            foreach (var site in parents)
            {
                var hasRoleInSite = permissionInSites.SingleOrDefault(x => x.SiteId == site.Id);
                var siteId = site.Id.ToString(CultureInfo.InvariantCulture);
                var trTags = new TagBuilder("li");

                var tdTags = new TagBuilder("span");
                tdTags.AddCssClass("cb");
                var inputTags = new TagBuilder("input");
                var attrs = hasRoleInSite != null ? new Dictionary<string, string> { { "type", "checkbox" }, { "value", siteId }, { "checked", "" } } : new Dictionary<string, string> { { "type", "checkbox" }, { "value", siteId } };
                inputTags.MergeAttributes(attrs);
                tdTags.InnerHtml += inputTags;
                trTags.InnerHtml += tdTags;

                tdTags = new TagBuilder("span");
                tdTags.MergeAttribute("class", "title col300 lev" + lev);
                var labelTags = new TagBuilder("label");
                labelTags.SetInnerText(site.Title);
                tdTags.InnerHtml += labelTags;
                trTags.InnerHtml += tdTags;

                tag.Append(trTags);
                var childrens = siteList.Where(x => x.ParentId == site.Id).ToList();
                if (childrens.Count > 0)
                {
                    lev++;
                    tag.Append(GetSubGrantPermissionTag(lev, site.Id, siteList, permissionInSites));
                    lev--;
                }
            }
            return MvcHtmlString.Create(tag.ToString());
        }

        /// <summary>
        /// Gets the sub grant permission tag.
        /// </summary>
        /// <param name="lev">The lev.</param>
        /// <param name="parentId">The parent identifier.</param>
        /// <param name="siteList">The site list.</param>
        /// <param name="permissionInSites">The permission in sites.</param>
        /// <returns></returns>
        public virtual MvcHtmlString GetSubGrantPermissionTag(int lev, int parentId, List<SiteDto> siteList, List<PermissionInSiteDto> permissionInSites)
        {
            var parents = siteList.Where(x => x.ParentId == parentId);
            var tag = new StringBuilder();
            foreach (var site in parents)
            {
                var hasRoleInSite = permissionInSites.SingleOrDefault(x => x.SiteId == site.Id);
                var siteId = site.Id.ToString(CultureInfo.InvariantCulture);
                var trTags = new TagBuilder("li");

                var tdTags = new TagBuilder("span");
                tdTags.AddCssClass("cb");
                var inputTags = new TagBuilder("input");
                var attrs = hasRoleInSite != null ? new Dictionary<string, string> { { "type", "checkbox" }, { "value", siteId }, { "checked", "" } } : new Dictionary<string, string> { { "type", "checkbox" }, { "value", siteId } };
                inputTags.MergeAttributes(attrs);
                tdTags.InnerHtml += inputTags;
                trTags.InnerHtml += tdTags;

                tdTags = new TagBuilder("span");
                tdTags.MergeAttribute("class", "title col300 lev" + lev);
                var labelTags = new TagBuilder("label");
                labelTags.SetInnerText(site.Title);
                tdTags.InnerHtml += labelTags;
                trTags.InnerHtml += tdTags;

                tag.Append(trTags);
                var childrens = siteList.Where(x => x.ParentId == site.Id).ToList();
                if (childrens.Count <= 0) continue;
                lev++;
                tag.Append(GetSubGrantPermissionTag(lev, site.Id, siteList, permissionInSites));
                lev--;
            }
            return MvcHtmlString.Create(tag.ToString());
        }
        #endregion
    }
}
